<template>
	<view>
		<view class="container">
			<!-- Header -->
			<view class="header">
				<text class="back-button" @click="returnPage"></text>
				<text class="title">购物车</text>
				<text class="manage" @click="toggleManage">{{ isManaging ? '完成' : '管理' }}</text>
			</view>

			<!-- Empty Cart Message -->
			<view v-if="cartItems.length === 0" class="empty-cart">
				<text>购物车是空的哦，快去加购心仪商品吧</text>
			</view>

			<!-- Cart Items -->
			<scroll-view v-else class="cart-list" scroll-y>
				<view v-for="(item, index) in cartItems" :key="index" class="cart-item">
					<view class="item-info">
						<checkbox class="checkmark" :checked="item.selected" @click="handleItemSelect(index)" />
						<image class="item-image" :src="item.image[0]"></image>
						<view class="item-details">
							<text class="item-title">{{ item.productName }}</text>
							<text class="item-price">${{ item.attributes.price }}</text>
						</view>
						<view class="item-quantity">
							<button @click="decreaseQuantity(index)">-</button>
							<text>{{ item.quantity }}</text>
							<button @click="increaseQuantity(index)">+</button>
						</view>
					</view>
				</view>
			</scroll-view>

			<view class="suggestions">
				<view class="biaoti">
					<text class="biaoti_yidong"><text class="henggang">—— </text>推荐商品<text class="henggang">
							——</text></text>
				</view>
				<view class="tuijian" v-for="(item,i) in suggestions" :key="i" @click="tuijian">
					<image :src="item.image[0]" alt="" class="dianpu">
						<text class="shopping_name">{{item.description}}</text>
						<text class="shopping_money">
							<text size="6rpx">￥{{item.attributes.price}}</text>
						</text>
						<text class="shopping_yuanjia"><del>￥1000</del></text>
						<text class="shopping_num">30w+已买</text>
						<view class="xinxi_x">
							<text class="xinxi">新客|退货包运费</text>
						</view>
				</view>
			</view>

			<!-- Total and Checkout -->
			<view class="checkout-bar">
				<checkbox class="select-all" :checked="selectAll" @click="toggleSelectAll" />
				<text>全选</text>
				<text class="total">总价: ￥{{ totalPrice }}</text>
				<button class="checkout-btn"
					@click="isManaging ? removeSelectedItems() : checkout()">{{ isManaging ? '删除' : '结算' }}</button>
			</view>
		</view>
		<u-loadmore :status="status" />
	</view>
</template>

<script>
	import {
		get
	} from 'request';
	export default {
		onLoad() {
			this.getData();
			this.getAll();
			 // 从本地存储获取 quantities 数据
			    const quantities = uni.getStorageSync('quantities');
			    
			    // 将字符串分割成数组并赋值给 data 中的 quantityArray
			    if (quantities) {
			      this.quantityArray = quantities.split(','); // 假设存储的 quantities 是用逗号分隔的字符串
			    }
		},
		onPullDownRefresh() {
			this.page = 1;
			this.suggestions = []; // 修复拼写错误
			this.getAll();
			setTimeout(() => {
				uni.stopPullDownRefresh();
			}, 1000);
		},
		onReachBottom() {
			if (this.total <= this.suggestions.length) { // 修复拼写错误
				uni.showToast({
					title: '已加载全部数据',
					icon: "none"
				});
			} else {
				this.page++;
				this.getAll();
			}
		},
		onReachBottom() {
			if (this.page >= 3) return;
			this.status = 'loading';
			this.page = ++this.page;
			setTimeout(() => {
				this.list += 10;
				if (this.page >= 3) this.status = 'nomore';
				else this.status = 'loading';
			}, 2000)
		},
		data() {
			return {
				status: 'loadmore',
				total: 0,
				cartItems: [{
					title: '',
					price: 10,
					image: '',
					productId: "",
					quantity: 1,
					selected: false
				}],
				suggestions: [{
						title: '',
						price: '',
						image: ''
					},
					{
						title: '',
						price: '',
						image: ''
					},
					{
						title: '',
						price: '',
						image: ''
					}
				],
				isManaging: false,
				productId: [],
				 quantityArray: [], // 用于存储从本地存储获取的 quantities 数组
				totalPrice: 0,
				selectAll: false,
				page: 1,
				size: 2,
			};
		},
		methods: {
			checkout() {
				// 在结算前，你可以添加一些验证逻辑，例如检查是否有选中的商品等
				if (this.totalPrice > 0) {
					const selectedItems = this.cartItems.filter(item => item.selected);
					const productIds = selectedItems.map(item => item.productId).join(',');
					const quantities = selectedItems.map(item => item.quantity); // 保持为数组
					uni.setStorageSync('quantities', quantities); // 直接存储为数组
								
								// uni.setStorageSync('quantities', quantities);
					uni.navigateTo({
						url: `/pages/payment/payment?productId=${productIds}&quantity=${quantities}`
					});
				} else {
					uni.showToast({
						title: '请选择至少一件商品进行结算',
						icon: 'none'
					});
				}
			},
			returnPage() {
				uni.navigateBack({
					delta: 1
				})
			},
			getData() {
				this.userId = uni.getStorageSync('id')
				this.request("/cart/getCartList", "get", {
					userId: this.userId
				}).then(
					(res) => {
						console.log(res);
						this.cartItems = res.data
						console.log(this.productId );

					}).catch((err) => {
					console.log(err);
				});
			},
			getAll() {
				this.request(`/shoppingAll/shoppingList?page=${this.page}&size=${this.size}`, "get").then(
					(res) => {
						console.log(res);
						this.total = res.data.result.result.list;
						this.productId =res.data.result.result.list.productId
						if (this.page === 1) {
							this.suggestions = res.data.result.result.list;

						} else {
							this.suggestions = this.suggestions.concat(res.data.result.result.list);
						}
					}).catch((err) => {
					console.log(err);
				});
			},
			toggleManage() {
				this.isManaging = !this.isManaging;
				if (!this.isManaging) {
					this.cartItems.forEach(item => item.selected = false);
					this.selectAll = false;

				}
			},
			handleItemSelect(e) {
				this.cartItems[e].selected = !this.cartItems[e].selected;
				if (this.cartItems[e].selected) {
					this.totalPrice += Number(this.cartItems[e].attributes.price) * Number(this.cartItems[e].quantity);
				} else {
					this.totalPrice -= Number(this.cartItems[e].attributes.price) * Number(this.cartItems[e].quantity);
				}
				this.totalPrice = parseFloat(this.totalPrice.toFixed(2)); // 限制总价为两位小数

				// Check if all items are selected to update the selectAll state
				const allSelected = this.cartItems.every(item => item.selected);
				this.selectAll = allSelected;
			},
			toggleSelectAll() {
				this.selectAll = !this.selectAll;
				for (let i = 0; i < this.cartItems.length; i++) {
					if (this.cartItems[i].selected !== this.selectAll) {
						this.cartItems[i].selected = this.selectAll;
						if (this.selectAll) {
							this.totalPrice += Number(this.cartItems[i].attributes.price) * Number(this.cartItems[i]
								.quantity);
						} else {
							this.totalPrice = 0; // 取消全选时重置总价
						}
					}
				}
				this.totalPrice = parseFloat(this.totalPrice.toFixed(2)); // 限制总价为两位小数
			},
			removeSelectedItems() {
			    this.userId = uni.getStorageSync('id');
			    const productIds = this.cartItems.filter(item => item.selected).map(item => item.productId);
			    const requestData = {
			        userId: this.userId,
			        productIds: productIds
			    };
			    
			    this.request("/cart/DeleteCart", "post", JSON.stringify(requestData), {
			        headers: {
			            'Content-Type': 'application/json'
			        }
			    }).then((res) => {
					this.as = res.data.code;
					 if(this.as == 200){
						 this.getData()
					 }
			        console.log(res);
			    }).catch((err) => {
			        console.log(err);
			    });
			},


			increaseQuantity(e) {
				if (Number(this.cartItems[e].quantity) >= 1) {
					this.cartItems[e].quantity++;
					if (this.cartItems[e].selected) {
						this.totalPrice += Number(this.cartItems[e].attributes.price);
					}
				}
				this.totalPrice = parseFloat(this.totalPrice.toFixed(2)); // 限制总价为两位小数
			},

			decreaseQuantity(e) {
				if (Number(this.cartItems[e].quantity) > 1) {
					this.cartItems[e].quantity--;
					if (this.cartItems[e].selected) {
						this.totalPrice -= Number(this.cartItems[e].attributes.price);
					}
				}
				this.totalPrice = parseFloat(this.totalPrice.toFixed(2)); // 限制总价为两位小数
			},
		}
	};
</script>

<style scoped>
	.dianpu {
		width: 100%;
		height: 360rpx;
	}

	.tuijian {
		width: 46%;
		height: 600rpx;
		background-color: #fff;
		justify-content: space-evenly;
		box-sizing: border-box;
		margin-top: 20rpx;
		margin-left: 20rpx;
		position: relative;
	}

	.shopping_name {
		display: block;
		width: 320rpx;
		position: absolute;
		top: 390rpx;
		left: 10rpx;

		font-size: 30rpx;
		overflow: hidden;
		/*内容超出后隐藏*/
		text-overflow: ellipsis;
		/*超出内容显示为省略号*/
		white-space: nowrap;
		/*文本不进行换行*/
	}

	.shopping_money {
		position: absolute;
		top: 440rpx;
		left: 4rpx;
		font-size: 30rpx;
	}

	.shopping_yuanjia {
		position: absolute;
		top: 437rpx;
		left: 200rpx;
		font-size: 28rpx;
		color: rgb(165, 165, 165);
	}

	.shopping_num {
		position: absolute;
		top: 480rpx;
		left: 10rpx;
		font-size: 28rpx;
		color: rgb(165, 165, 165);
	}

	.xinxi_x {

		height: 40rpx;
		border: 2rpx solid rgb(165, 165, 165);
		border-radius: 10rpx;
		position: absolute;
		top: 520rpx;
		left: 10rpx;
		font-size: 25rpx;

	}

	.biaoti {
		width: 100%;
		height: 80rpx;
		background-color: rgb(243, 243, 243);

		position: relative;
	}

	.biaoti>.biaoti_yidong {
		font-size: 40rpx;
		font-weight: 600;
		text-align: center;
		display: inline;
		position: absolute;
		top: 20rpx;
		left: 220rpx;
	}

	.henggang {
		color: rgb(212, 212, 212);

	}

	.suggestions {

		width: 100%;

		background-color: rgb(243, 243, 243);
		display: flex;
		flex-wrap: wrap;
	}

	.back-button::before {
		font-family: "iconfont" !important;
		content: "\e64e";
		font-size: 50rpx;
		color: black;
	}

	.container {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f8f8f8;
	}

	.header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 20px;
		background-color: #fff;
		border-bottom: 1px solid #e0e0e0;
	}

	.back-button {
		font-size: 18px;
		color: #000;
	}

	.title {
		font-size: 20px;
		font-weight: bold;
	}

	.manage {
		font-size: 18px;
		color: #007aff;
	}

	.empty-cart {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		color: #888;
	}

	.cart-list {
		flex: 1;
		padding: 10px;
		background-color: #f5f5f5;
	}

	.cart-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px;
		background-color: #fff;
		margin-bottom: 10px;
		border-radius: 5px;
		box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
	}

	.item-info {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.checkmark {
		margin-right: 10px;
	}

	.item-image {
		width: 80px;
		height: 80px;
		margin-right: 10px;
		border-radius: 5px;
		object-fit: cover;
	}

	.item-details {
		display: flex;
		flex-direction: column;
		justify-content: center;
		flex: 1;
	}

	.item-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 5px;
	}

	.item-price {
		font-size: 14px;
		color: #f40;
	}

	.item-quantity {
		display: flex;
		align-items: center;
		margin-left: 10px;
	}

	.item-quantity button {
		width: 25px;
		height: 25px;
		background-color: #007aff;
		color: white;
		border: none;
		text-align: center;
		line-height: 25px;
		border-radius: 5px;
	}

	.item-quantity text {
		margin: 0 5px;
		font-size: 14px;
	}

	.suggestions {
		background-color: #fff;
		padding: 10px;
	}

	.suggestions-title {
		font-size: 16px;
		font-weight: bold;
		margin-bottom: 10px;
	}

	.suggestions-list {
		display: flex;
		overflow-x: auto;
	}

	.suggestion-item {
		width: 50%;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-right: 10px;
	}

	.suggestion-image {
		width: 100px;
		height: 100px;
		margin-bottom: 5px;
		border-radius: 5px;
		object-fit: cover;
	}

	.suggestion-title {
		font-size: 14px;
		margin-bottom: 5px;
		text-align: center;
	}

	.suggestion-price {
		font-size: 14px;
		color: #f40;
	}

	.checkout-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 20px;
		background-color: #fff;
		border-top: 1px solid #e0e0e0;
		position: sticky;
		bottom: 0;
		left: 0;
		right: 0;
	}

	.select-all {
		display: flex;
		align-items: center;
	}

	.total {
		font-size: 16px;
		font-weight: bold;
	}

	.checkout-btn {
		background-color: #f40;
		color: white;
		border: none;
		padding: 10px 20px;
		border-radius: 5px;
		font-size: 16px;
	}
</style>